package com.googlecode.cswish.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class FileUtil {
	private static final Logger logger = Logger.getLogger(FileUtil.class);
	
	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
	
	public static String saveFile(InputStream input, String path, String filename, boolean autoRename) {
		File saveFile;
		String newfilename;
		if (autoRename) {
			newfilename = System.currentTimeMillis() + "." + filename;
			saveFile = new File(path + newfilename);
			// avoid the dupli name
			while (saveFile.exists()) {
				filename = System.currentTimeMillis() + filename;
				saveFile = new File(path + newfilename);
			}
		} else {
			newfilename = filename;
			saveFile = new File(path + newfilename);
		}
		
		try {
			saveFile.getParentFile().mkdirs();
			saveFile.createNewFile();
			byte [] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int len;
			
			FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
			while ((len = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
				fileOutputStream.write(buffer, 0, len);
			}
			
			fileOutputStream.close();
		} catch (Exception ex) {
			logger.error(ex);
			
			return null;
		}
		
		return newfilename;
	}
	
	public static void export(HttpServletResponse response, String path, String filename) throws Exception {
		int index = filename.lastIndexOf('.');
		String contentType;
		if (index > 0) {
			contentType = filename.substring(index + 1);
		} else {
			contentType = "";
		}
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", "filename=" + filename);
		int length = (int)new File(filename).length();
		response.setContentLength(length);		
		
		ServletOutputStream output = response.getOutputStream();
		
		byte [] buffer = new byte[DEFAULT_BUFFER_SIZE];
		int len;
		FileInputStream input = new FileInputStream(path + filename);
		while ((len = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
			output.write(buffer, 0, len);
		}
		input.close();
		output.flush();
		output.close();
	}
	
	/**
	 * 
	 * @param input
	 * @param encoding
	 * @return
	 * 
	 * @see org.apache.commons.io.FileUtils
	 */
	public static String readFileToString(InputStream input, String encoding) {
		StringWriter sw = new StringWriter();
		
		char[] buffer = new char[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        try {
	        InputStreamReader in = new InputStreamReader(input, encoding);
	        while (-1 != (n = in.read(buffer))) {
	            sw.write(buffer, 0, n);
	            count += n;
	        }    
			return sw.toString();
        } catch (IOException ex) {
        	logger.error("Read input strean", ex);
        }
        return null;
	}
}
